package com.children.growth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.children.growth.entity.VoiceLog;
import com.children.growth.mapper.VoiceLogMapper;
import com.children.growth.service.SpeechRecognitionService;
import com.children.growth.service.VoiceLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 语音日志服务实现类
 * 
 * @author children
 * @since 1.0.0
 */
@Service
public class VoiceLogServiceImpl extends ServiceImpl<VoiceLogMapper, VoiceLog> implements VoiceLogService {

    @Autowired
    private SpeechRecognitionService speechRecognitionService;

    private static final String UPLOAD_DIR = "uploads/audio/";
    private static final String PROCESSED_DIR = "uploads/processed/";

    @Override
    public boolean createVoiceLog(VoiceLog voiceLog, MultipartFile audioFile) {
        try {
            // 创建上传目录
            createUploadDirectories();
            
            // 生成唯一文件名
            String originalFileName = audioFile.getOriginalFilename();
            String fileExtension = getFileExtension(originalFileName);
            String fileName = UUID.randomUUID().toString().concat(fileExtension);
            
            // 保存原始音频文件
            String originalPath = UPLOAD_DIR.concat(fileName);
            Path originalFilePath = Paths.get(originalPath);
            Files.copy(audioFile.getInputStream(), originalFilePath);
            
            // 处理音频文件（降噪、压缩等）
            String processedPath = processAudioFile(originalPath, fileName);
            
            // 设置语音日志信息（存储URL路径）
            voiceLog.setAudioPath("/" + originalPath);
            voiceLog.setProcessedAudioPath("/" + processedPath);
            voiceLog.setDuration(calculateDuration(audioFile));
            voiceLog.setFileSize(audioFile.getSize());
            voiceLog.setCreateTime(LocalDateTime.now());
            voiceLog.setUpdateTime(LocalDateTime.now());
            
            // 语音转文字
            String text = speechRecognitionService.speechToText(audioFile);
            voiceLog.setContent(text);
            
            // 情感分析
            Map<String, Object> emotionResult = analyzeEmotionDetailed(text);
            voiceLog.setEmotion(((Integer) emotionResult.get("emotion")).intValue());
            voiceLog.setEmotionScore(((Integer) emotionResult.get("score")).intValue());
            
            // 生成标签
            String tags = generateTags(text, ((Integer) emotionResult.get("emotion")).intValue());
            voiceLog.setTags(tags);
            
            return save(voiceLog);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Page<VoiceLog> getVoiceLogList(Long userId, Integer pageNum, Integer pageSize, String emotion, String keyword, String startDate, String endDate) {
        Page<VoiceLog> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<VoiceLog> wrapper = new LambdaQueryWrapper<>();
        
        // 基础条件：用户ID
        wrapper.eq(VoiceLog::getUserId, userId);
        
        // 情感筛选
        if (emotion != null && !emotion.trim().isEmpty()) {
            try {
                Integer emotionValue = Integer.parseInt(emotion);
                wrapper.eq(VoiceLog::getEmotion, emotionValue);
            } catch (NumberFormatException e) {
                // 如果转换失败，忽略此筛选条件
                System.err.println("情感值格式错误: " + emotion);
            }
        }
        
        // 关键词搜索（标题和内容）
        if (keyword != null && !keyword.trim().isEmpty()) {
            wrapper.and(w -> w.like(VoiceLog::getTitle, keyword)
                              .or()
                              .like(VoiceLog::getContent, keyword));
        }
        
        // 日期范围筛选
        if (startDate != null && !startDate.trim().isEmpty()) {
            try {
                LocalDateTime startDateTime = LocalDateTime.parse(startDate + "T00:00:00");
                wrapper.ge(VoiceLog::getCreateTime, startDateTime);
            } catch (Exception e) {
                // 日期格式错误，忽略此筛选条件
                System.err.println("开始日期格式错误: " + startDate);
            }
        }
        
        if (endDate != null && !endDate.trim().isEmpty()) {
            try {
                LocalDateTime endDateTime = LocalDateTime.parse(endDate + "T23:59:59");
                wrapper.le(VoiceLog::getCreateTime, endDateTime);
            } catch (Exception e) {
                // 日期格式错误，忽略此筛选条件
                System.err.println("结束日期格式错误: " + endDate);
            }
        }
        
        // 按创建时间倒序排列
        wrapper.orderByDesc(VoiceLog::getCreateTime);
        
        return page(page, wrapper);
    }

    @Override
    public VoiceLog getVoiceLogById(Long id) {
        return getById(id);
    }

    @Override
    public boolean updateVoiceLog(VoiceLog voiceLog) {
        voiceLog.setUpdateTime(LocalDateTime.now());
        return updateById(voiceLog);
    }

    @Override
    public boolean deleteVoiceLog(Long id) {
        VoiceLog voiceLog = getById(id);
        if (voiceLog != null) {
            // 删除音频文件
            deleteAudioFile(voiceLog.getAudioPath());
            deleteAudioFile(voiceLog.getProcessedAudioPath());
        }
        return removeById(id);
    }



    @Override
    public String analyzeEmotion(String text) {
        // 这里应该调用AI服务进行情感分析
        // 暂时使用基于关键词的简单分析
        Map<String, Object> result = analyzeEmotionDetailed(text);
        return result.get("emotion").toString();
    }

    @Override
    public Object getVoiceStatistics(Long userId) {
        LambdaQueryWrapper<VoiceLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VoiceLog::getUserId, userId);
        
        long totalCount = count(wrapper);
        
        // 统计情感分布
        long happyCount = count(wrapper.eq(VoiceLog::getEmotion, 1)); // 开心
        long calmCount = count(wrapper.eq(VoiceLog::getEmotion, 2)); // 平静
        long sadCount = count(wrapper.eq(VoiceLog::getEmotion, 3)); // 难过
        long angryCount = count(wrapper.eq(VoiceLog::getEmotion, 4)); // 愤怒
        long anxiousCount = count(wrapper.eq(VoiceLog::getEmotion, 5)); // 焦虑
        
        // 计算平均情感分数，处理null值情况
        Double emotionScoreResult = baseMapper.selectAvgEmotionScore(userId);
        double avgEmotionScore = emotionScoreResult != null ? emotionScoreResult : 0.0;
        
        // 统计最近7天的记录
        LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
        long recentCount = count(wrapper.ge(VoiceLog::getCreateTime, sevenDaysAgo));
        
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalCount", totalCount);
        statistics.put("happyCount", happyCount);
        statistics.put("calmCount", calmCount);
        statistics.put("sadCount", sadCount);
        statistics.put("angryCount", angryCount);
        statistics.put("anxiousCount", anxiousCount);
        statistics.put("avgEmotionScore", avgEmotionScore);
        statistics.put("recentCount", recentCount);
        
        return statistics;
    }

    /**
     * 创建上传目录
     */
    private void createUploadDirectories() throws IOException {
        Path uploadPath = Paths.get(UPLOAD_DIR);
        Path processedPath = Paths.get(PROCESSED_DIR);
        
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        if (!Files.exists(processedPath)) {
            Files.createDirectories(processedPath);
        }
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String fileName) {
        if (fileName == null || !fileName.contains(".")) {
            return ".wav";
        }
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 处理音频文件
     */
    private String processAudioFile(String originalPath, String fileName) {
        try {
            // 这里应该进行音频处理（降噪、压缩等）
            // 暂时直接复制原文件
            String processedPath = PROCESSED_DIR.concat("processed_").concat(fileName);
            Path source = Paths.get(originalPath);
            Path target = Paths.get(processedPath);
            Files.copy(source, target);
            return processedPath;
        } catch (IOException e) {
            e.printStackTrace();
            return originalPath;
        }
    }

    /**
     * 删除音频文件
     */
    private void deleteAudioFile(String filePath) {
        if (filePath != null) {
            try {
                Path path = Paths.get(filePath);
                if (Files.exists(path)) {
                    Files.delete(path);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 计算音频时长
     */
    private Integer calculateDuration(MultipartFile audioFile) {
        try {
            // 这里应该解析音频文件获取实际时长
            // 暂时根据文件大小估算
            long fileSize = audioFile.getSize();
            // 假设16kbps的音频，估算时长
            return (int) (fileSize / 2000); // 粗略估算
        } catch (Exception e) {
            return 30; // 默认30秒
        }
    }

    /**
     * 详细的情感分析
     */
    private Map<String, Object> analyzeEmotionDetailed(String text) {
        Map<String, Object> result = new HashMap<>();
        
        // 情感关键词分析
        int happyScore = countKeywords(text, new String[]{"开心", "高兴", "快乐", "棒", "好", "喜欢", "爱"});
        int sadScore = countKeywords(text, new String[]{"难过", "伤心", "不开心", "哭", "失望", "沮丧"});
        int angryScore = countKeywords(text, new String[]{"生气", "愤怒", "讨厌", "恨", "烦"});
        int anxiousScore = countKeywords(text, new String[]{"担心", "害怕", "紧张", "焦虑", "压力"});
        
        // 确定主要情感
        int maxScore = Math.max(Math.max(happyScore, sadScore), Math.max(angryScore, anxiousScore));
        
        int emotion;
        int score;
        
        if (maxScore == happyScore && happyScore > 0) {
            emotion = 1; // 开心
            score = 80 + (happyScore * 5);
        } else if (maxScore == sadScore && sadScore > 0) {
            emotion = 3; // 难过
            score = 20 + (sadScore * 10);
        } else if (maxScore == angryScore && angryScore > 0) {
            emotion = 4; // 愤怒
            score = 30 + (angryScore * 15);
        } else if (maxScore == anxiousScore && anxiousScore > 0) {
            emotion = 5; // 焦虑
            score = 40 + (anxiousScore * 12);
        } else {
            emotion = 2; // 平静
            score = 50;
        }
        
        result.put("emotion", emotion);
        result.put("score", Math.min(100, Math.max(0, score)));
        
        return result;
    }

    /**
     * 生成标签
     */
    private String generateTags(String text, int emotion) {
        // 这里应该根据情感和文本内容生成标签
        // 暂时返回固定标签
        if (emotion == 1) {
            return "开心,快乐,棒";
        } else if (emotion == 3) {
            return "难过,伤心,沮丧";
        } else if (emotion == 4) {
            return "生气,愤怒,讨厌";
        } else if (emotion == 5) {
            return "担心,害怕,焦虑";
        } else {
            return "平静,正常";
        }
    }

    /**
     * 计算关键词出现次数
     */
    private int countKeywords(String text, String[] keywords) {
        int count = 0;
        for (String keyword : keywords) {
            if (text.contains(keyword)) {
                count++;
            }
        }
        return count;
    }
}